package cn.itcast.demo.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class PaiziFilter extends ZuulFilter {
    /**
     * filter的类型
     * 四种  pro,post,routing,error
     * <p>
     * type==pro
     * <p>
     * pre-->routing--->post
     * <p>
     * pro-->error-->post
     * <p>
     * pre-->routing--->error-->post
     * <p>
     * pre-->routing--->post--->error
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 决定是否启用这个过滤器
     * <p>
     * true 生效
     * <p>
     * false 过滤器不生效
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }


    /**
     * 过滤器生效后的逻辑，是否放行就在这里决定了
     * <p>
     * 拦截要单独处理，放行不理会
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
//        获取当前请求的资源管理器
        RequestContext currentContext = RequestContext.getCurrentContext();

//        获取request对象
        HttpServletRequest request = currentContext.getRequest();
        String paizi = request.getParameter("paizi");

//        没有符合我们的要求，此时拦截，拦截就是不响应
        if (StringUtils.isEmpty(paizi)) {
            currentContext.setSendZuulResponse(false);//声明不响应

            currentContext.setResponseStatusCode(401);//未授权
        }


        return null;
    }
}
